import pathToRegexp from 'path-to-regexp';
import { getUploadToken } from '../services/qiniu';
import { submitQualificationns } from '../services/register';
import { getLocalStorage } from '../utils/storage';

export default {
  namespace: 'doctorLic',
  state: {
    uploadToken: '',
    image1Url: '',
    image2Url: '',
    buttonStatus: true,
  },
  reducers: {
    uploadImage1Success(state, { payload }) {
      if (state.image2Url !== '') {
        return { ...state, buttonStatus: false, image1Url: payload };
      } else {
        return { ...state, buttonStatus: true, image1Url: payload };
      }
    },
    uploadImage2Success(state, { payload }) {
      if (state.image1Url !== '') {
        return { ...state, buttonStatus: false, image2Url: payload };
      } else {
        return { ...state, buttonStatus: true, image2Url: payload };
      }
    },
    fetchUploadTokenSuccess(state, { payload }) {
      return { ...state, uploadToken: payload };
    },
  },
  effects: {
    *fetchUploadToken({ payload }, { call, put }) {
      const { data } = yield call(getUploadToken, payload);
      yield put({
        type: 'fetchUploadTokenSuccess',
        payload: data.token,
      });
    },
    *submit({ payload }, { select, call }) {
      const image1 = yield select(({ doctorLic }) => doctorLic.image1Url);
      const image2 = yield select(({ doctorLic }) => doctorLic.image2Url);
      const { err } = yield call(submitQualificationns, {
        qualificationImages: [image1, image2],
      });
      if (!err) {
        // alert('提交医师资料成功，请关闭页面');
      } else {
        err.json.then(errJson => alert(errJson.errMessage));
      }
    },
  },
  subscriptions: {
    setup({ dispatch, history }) {
      history.listen((location) => {
        const match = pathToRegexp('/uploadDoctorLic').exec(location.pathname);
        if (match) {
          const token = getLocalStorage('access_token');
          if (token) {
            dispatch({
              type: 'fetchUploadToken',
              payload: {
                token,
                bucket: 'certification',
                insertOnly: 0,
              },
            });
          }
        }
      });
    },
  },
};
